package com.qf.cx.simplenms.link.api;

public interface LinkManager {

	boolean startListen(int port);

	Link establish(ReaderSource readerSource);

	void close(ReaderSource readerSource);

	/**
	 * reader 连接类型，SERVER表示reader作为服务端
	 * 
	 * @author whm
	 *
	 */
	enum LinkType {
		CLIENT(0) {
			@Override
			public String getReaderIdentifier(String ip, int port, String sn) {
				return sn;
			}
		},
		SERVER(1) {
			@Override
			public String getReaderIdentifier(String ip, int port, String sn) {
				return ip + "-" + port;
			}
		};
		private int value;

		private LinkType(int value) {
			this.value = value;
		}

		public int getValue() {
			return value;
		}
		
		abstract public String getReaderIdentifier(String ip, int port, String sn);

		public static LinkType valueOf(int a) {
			LinkType[] values = values();
			for (LinkType type : values) {
				if (type.getValue() == a) {
					return type;
				}
			}
			return null;
		}
	}

	class ReaderSource {

		/**
		 * can be null
		 */
		private String deviceSn;
		/**
		 * can be null
		 */
		private String ip;
		/**
		 * can be null
		 */
		private int port;
		private LinkType linkType;

		public String getDeviceSn() {
			return deviceSn;
		}

		public void setDeviceSn(String deviceSn) {
			this.deviceSn = deviceSn;
		}

		public String getIp() {
			return ip;
		}

		public void setIp(String ip) {
			this.ip = ip;
		}

		public int getPort() {
			return port;
		}

		public void setPort(int port) {
			this.port = port;
		}

		public LinkType getLinkType() {
			return linkType;
		}

		public void setLinkType(int type) {
			this.linkType = LinkType.valueOf(type);
		}

		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + ((deviceSn == null) ? 0 : deviceSn.hashCode());
			result = prime * result + ((ip == null) ? 0 : ip.hashCode());
			result = prime * result + port;
			result = prime * result + ((linkType == null) ? 0 : linkType.hashCode());
			return result;
		}

		@Override
		public boolean equals(Object obj) {
			if (this == obj) {
				return true;
			}
			if (obj == null) {
				return false;
			}
			if (getClass() != obj.getClass()) {
				return false;
			}
			ReaderSource other = (ReaderSource) obj;
			if (deviceSn == null) {
				if (other.deviceSn != null) {
					return false;
				}
			} else if (!deviceSn.equals(other.deviceSn)) {
				return false;
			}
			if (ip == null) {
				if (other.ip != null) {
					return false;
				}
			} else if (!ip.equals(other.ip)) {
				return false;
			}
			if (port != other.port) {
				return false;
			}
			if (linkType != other.linkType) {
				return false;
			}
			return true;
		}

		@Override
		public String toString() {
			return "ReaderSource [deviceSn=" + deviceSn + ", ip=" + ip + ", port=" + port + ", linkType=" + linkType + "]";
		}

		public String getReaderIdentifier() {
			return linkType.getReaderIdentifier(this.getIp(), this.getPort(), this.getDeviceSn());
		}

	}

}
